<template>
    <!-- 查询部分 -->
    <pageTabelLayout>
        <template #pageHeader>
            <div style="float:right">
                <Toolbar :items="['新增', '删除', '计算','保存']" @add="showInsertForm" @del="deleteHandler"
                    @compute="computeStatistics" @saveData="updateFormulas"></Toolbar>
            </div>
        </template>

        <template #pageTabel>
              <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true" rowSelection="multiple" @grid-ready="gridReady"
                style="height:calc(100% - 45px);" class='ag-theme-alpine'
                :defaultColDef="defaultColDef" :rowData="tableDataList" :columnDefs="columnDefs" :gridOptions="gridOptions"
                :suppressDragLeaveHidesColumns="true" :localeText="localeTextData">
            </AgGridVuesCopys>
            <paginationCopys :total="searchData.total" show-total style="justify-content: center;margin-bottom:18px" @change="pageChange"
            :current="searchData.current" :page-size="searchData.size"></paginationCopys>
        </template>
       
        <a-drawer :drawer-style="{ 'zIndex': 999 }" :mask-closable="false" unmount-on-close
            popup-container=".arco-tabs-content" :height="pageData.rHeight" :visible="pageData.showAdd" 
            placement="bottom" :footer="false" @ok="handleOk" @cancel="handleCancel">
            <template #title>
                {{ pageData.sideTitle }}
            </template>
            <div style="width:35%;margin-top: 10px;float: left;">
                <a-form ref="formRef" :model="formData" layout="horizontal">
                    <a-form-item field="statisticsName" label="统计名称" :rules="[{ required: true, message: '统计名称' }]"
                        :validate-trigger="['change', 'blur']" label-col-flex="80px">
                        <a-input class="bacClass" v-model="formData.statisticsName" placeholder="" />
                    </a-form-item>
                    <a-form-item field="statisticsType" label="资源类别" label-col-flex="80px">
                        <a-select popup-container="html"  class="bacClass" v-model="formData.statisticsType" :filter-option="false" default-value='1'>
                            <a-option value="1">用水量</a-option>
                            <a-option value="2">用电量</a-option>
                            <a-option value="3">低压蒸汽</a-option>
                            <a-option value="4">中压蒸汽</a-option>
                            <a-option value="5">湿开幅用水量</a-option>
                            <a-option value="6">拉针机用电量</a-option>
                            <a-option value="7">拉针机低压蒸汽</a-option>
                            <a-option value="8">定型机用水量</a-option>
                            <a-option value="9">定型机低压蒸汽</a-option>
                            <a-option value="10">静电除烟用水</a-option>
                            <a-option value="11">预缩机低压蒸汽</a-option>
                            <a-option value="12">前处理用水</a-option>
                            <a-option value="13">前处理用电</a-option>
                            <a-option value="14">前处理低压蒸汽</a-option>
                            <a-option value="15">地下热水回收到水</a-option>
                            <a-option value="16">预缩机低压蒸汽</a-option>
                        </a-select>
                    </a-form-item>
                    <a-form-item label="所属公司" field="companyName" label-col-flex="80px">
                        <a-input class="bacClass" placeholder="" v-model.trim="formData.companyName" :disabled='true' />
                        <a-input class="bacClass" placeholder="" v-model.trim="formData.companyId" v-show='false' />
                    </a-form-item>
                    <a-form-item label="所属部门" :rules="[{ required: true, message: '部门必填' }]" field="departmentId" label-col-flex="80px">
                        <a-cascader v-model="formData.departmentId" :options="pageData.departmentList" allow-clear
                            ref="departmentSelect" :class="bacClass" :title="pageData.title1"   popup-container="html"/>
                    </a-form-item>
                    <a-form-item field="formulaExpr" label="公式内容" :rules="[{ required: true, message: '公式内容必填' }]"
                        :validate-trigger="['change', 'blur']" label-col-flex="80px">
                        <a-textarea style="height:120px" class="bacClass" v-model="formData.formulaExpr"
                            :auto-size="{ minRows: 2, maxRows: 20 }" allow-clear show-word-limit />
                    </a-form-item>
                    <a-form-item label="测试公式" field="companyName" label-col-flex="80px">
                        <a-input class="bacClass" placeholder="" v-model.trim="formData.result" :disabled='true' />
                    </a-form-item>
                    <a-space style="margin-left:30%">
                        <a-button style="width:70px;" @click="evalExpr">测试</a-button>
                        <a-button style="width:70px;" @click="pageData.showAdd = false">关闭</a-button>
                        <a-button style="width:70px;background: #165DFF;color:white;" @click="addStatistics">保存</a-button>
                    </a-space>

                </a-form>
            </div>
            <div style="width:64%;height:100%;float: right">
                  <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true" @grid-ready="consumeGridReady" @row-double-clicked="rowDoubleClicked"
                    style="width:99%;height:97%;float:right;margin-top:10px" class='ag-theme-alpine'
                    :defaultColDef="defaultColDef" :rowData="consumeDataList" :columnDefs="consumeColDefs"
                    :gridOptions="consumeGridOptions">
                </AgGridVuesCopys>
            </div>
            <div style="width:64%;height:30px;float: right">
            <paginationCopys :total="pager.total" show-total style="justify-content: center" @change="consumePageChange"
                            :current="pager.current"></paginationCopys></div>
        </a-drawer>
    </pageTabelLayout>
</template>


<script lang="ts">
import { onMounted, reactive, ref } from 'vue';
import Toolbar from '@/components/Toolbar.vue';
import { post, get } from '@/api/http'
import { Message, Modal } from '@arco-design/web-vue'
import pagination from "@arco-design/web-vue/es/pagination";
import { FormInstance } from "@arco-design/web-vue/es/form";

import { localeText } from '@/api/aggridZw'
import PageTabelLayout from "@/components/pageTabelLayout.vue";
import CorporateSectorCascader from '@/components/corporateSectorCascader/inde.vue'
import { slicing } from '@/utils/caseFrimAndSecRig'

const localeTextData: any = ref(localeText);
const headerShow = ref<boolean>(true)


interface MeterEntity {
    meterNo: string,
    meterName: string,
    meterId: string
}

export default {

    setup() {

        const pager = reactive({
            total: 10,
            current: 1,
            size: 10
        });

        let searchData = reactive<{
            equipmentId: string,
            companyId: number,
            total: number | string,
            current: number,
            size: number
        }>({
            equipmentId: null,
            companyId: 0,
            total: 10,
            current: 1,
            size: 10
        });



        const pageData = reactive<{
            showAdd: boolean,
            sideTitle: string,
            departmentList: any[],
            pageLoading: boolean,
            headerShow: boolean,
            isShow: boolean,
            rHeight: any,
        }>({
            showAdd: false,
            sideTitle: "",
            departmentList: [],
            pageLoading: false,
            headerShow: true,
            isShow: false,
            rHeight: 0,
        })

        const formData = reactive({
            statisticsName:'',
            statisticsType:'',
            companyName: '',
            companyId: null,
            departmentName: '',
            departmentId: null,
            formulaExpr: '',
            result:''
        });

        const defaultColDef = {
            sortable: true,
            resizable: true,
            filter: true

        }

        const columnDefs = [
            {
                showRowGroup: 'hide_def',
                "checkboxSelection": true,
                "headerCheckboxSelection": true,
                "pinned": "left",
                "width": 150,
                sortable: false,
                minWidth: 50,
                maxWidth: 50,
                lockPosition: "left",
            },
            {
                headerName: 'ID',
                field: 'id',
                hide: true,
                width: 227
            },
            {
                headerName: '统计名称',
                field: 'statisticsName',
                editable: true,
                width: 227
            },
            {
                headerName: '资源类别',
                field: 'statisticsType',
                cellRenderer: params => {
                    let type='';
                    switch (params.value) {
                       case 1:
                         type = '用水量';  break;
                       case 2:
                         type = '用电量';  break;
                       case 3:
                         type = '低压蒸汽';  break;
                       case 4:
                         type = '中压蒸汽';  break;
                       case 5:
                         type = '湿开幅用水量';  break;
                       case 6:
                         type = '拉针机用电量';  break;
                       case 7:
                         type = '拉针机低压蒸汽';  break;
                    }
                    return type
                },
                width: 227
            },
            {
                headerName: '所属公司',
                field: 'companyName',
                width: 227
            },
            {
                headerName: '所属部门',
                field: 'departmentName',
                width: 227
            },
            {
                headerName: '公式内容',
                field: 'formulaExpr',
                editable: true,
                width: 227
            },
            {
                headerName: "创建人",
                field: "createUser",
                width: 227
            },
            {
                headerName: "创建日期",
                field: "createTime",
                width: 227
            }
        ]


        const consumeColDefs = [
            {
                showRowGroup: 'hide_def',
                "checkboxSelection": true,
                "headerCheckboxSelection": true,
                "pinned": "left",
                "width": 50,
                sortable: false,
                minWidth: 50,
                maxWidth: 50,
                lockPosition: "left",
            },
            {
                headerName: '设备编号',
                field: 'meterNo',
                width: 150
            },
            {
                headerName: '设备名称',
                field: 'meterName',
                width: 150
            },
            {
                headerName: '计数日期',
                field: 'createTime',
                width: 150
            },
            {
                headerName: '上次读数',
                field: 'lastCount',
                editable: true,
                width: 150
            },
            {
                headerName: '本次读数',
                field: 'thisCount',
                editable: true,
                width: 150
            },
            {
                headerName: '使用数',
                field: 'useCount',
                valueGetter: 'data.thisCount-data.lastCount',
                width: 150
            }
        ]



        let tableDataList = ref([]);
        let gridOptions = ref();
        let consumeGridOptions = ref();
        let consumeDataList = ref([]);


        const gridReady = (params: any) => {
            gridOptions = params.api;

        }

        const consumeGridReady = (params: any) => {
            consumeGridOptions = params.api;
            loadConsumes();
        }


        const loadConsumes = () => {
            pageData.pageLoading = true;
            console.log(searchData.companyId);
            post({
                url: "ems/energyConsume/findLastTimeConsumes",
                data: searchData
            })
                .then(({ data, code }: any) => {
                    if (code === 200) {
                        console.log(gridOptions);
                        pageData.pageLoading = false;
                        searchData.total = data.total;
                        consumeGridOptions.setRowData(data.records);
                        consumeDataList.value = data.records;
                    }
                });
        }


        const loadStatistics = () => {
            pageData.pageLoading = true;
            console.log(searchData.companyId);
            post({
                url: "ems/energyStatistics/findPagedStatistics",
                data: searchData
            })
                .then(({ data, code }: any) => {
                    if (code === 200) {
                        console.log(gridOptions);
                        searchData.total = data.total;
                        gridOptions.setRowData(data.records);
                        tableDataList.value = data.records;
                    }
                });
        }

        // 公司下拉框 改变
        const loadDepartmentList = (param) => {
            post({
                url: 'org/baCompany/getDepartmentTree?companyId=' + param,
            }).then((result) => {
                if (result.code === 200) {
                    pageData.departmentList = result.data
                }
            })
        };

        const pageChange = (val: any) => {
            searchData.current = val;
            loadStatistics();
        }

        const consumePageChange = (val: any) => {
            pager.current = val;
            loadConsumes();
        }

        onMounted(() => {
            initData();

            pageData.rHeight = document.getElementsByClassName("arco-tabs-content")[0]?.clientHeight
            //弹出层的高
            if (pageData.rHeight !== undefined) {
                pageData.rHeight = pageData.rHeight;
            }
            window.addEventListener('resize', () => {
                pageData.rHeight = document.getElementsByClassName("arco-tabs-content")[0]?.clientHeight
                //弹出层的高
                if (pageData.rHeight !== undefined) {
                    pageData.rHeight = pageData.rHeight;
                }
            })
        })


        const handleOk = () => {
            pageData.showAdd = false;
        };
        const handleCancel = () => {
            pageData.showAdd = false;
        }

        const initData = () => {
            post({
                url: 'ems/common/fetchUserInfoByToken',
                async: false,
                data: {}
            }).then(({ code, message, data }) => {
                if (code === 200) {
                    formData.companyName = data.firmName;
                    formData.companyId = data.firmId;
                    console.log(data.firmId);
                    searchData.companyId = data.firmId;
                    loadDepartmentList(data.firmId);
                    loadStatistics();
                } else {
                    Message.error({
                        content: message,
                        duration: 5000,
                    });
                }
            })
        }


        const showInsertForm = () => {
            pageData.showAdd = true;
            pageData.sideTitle = "新增统计";
        };

        const formRef = ref<FormInstance>();

        const addStatistics = () => {
            formRef.value?.validate().then((err) => {
                if (!err) {
                    let department = pageData.departmentList.find(item=>item.value==formData.departmentId);
                    console.log(department);
                    formData.departmentName = department.label;
                    post({
                        url: "ems/energyStatistics/saveStatistics",
                        data: formData
                    }).then((res: any) => {
                        if (res.code === 200) {
                            formRef.value?.resetFields();
                            pageData.showAdd = false;
                            Message.success({
                                content: "新增成功",
                                duration: 5000,
                            });
                            //将列表重置为第一页
                            searchData.current = 1;
                            loadStatistics();
                        }
                    });
                }
            });
        };


        const updateFormulas = () => {
            console.log(tableDataList.value);
            post({
                url: "ems/energyStatistics/batchUpdateStatistics",
                data: tableDataList.value
            })
                .then(({ data, code }: any) => {
                    if (code === 200) {
                        loadStatistics();
                    }
                });
        }


        const deleteHandler = () => {
            let rowIds = gridOptions.getSelectedRows().map((item) => item.id)
            if (rowIds.length === 0) {
                Message.warning("请选择要删除的数据！");
                return;
            }
            Modal.confirm({
                title: "系统提示",
                content: "确认删除选中的数据?",
                onOk() {
                    post({
                        url: "ems/energyStatistics/deleteStatistics",
                        data: rowIds,
                    }).then(({ code, data, message }: any) => {
                        if (code === 200) {
                            Message.success({
                                content: "删除成功",
                                duration: 5000,
                            });
                            loadStatistics();
                        }

                    });
                },
            });
        }


        const  computeStatistics =()=> {
            console.log(gridOptions.getSelectedRows());
            let exprList = gridOptions.getSelectedRows();
            let rowIds = gridOptions.getSelectedRows().map((item) => item.id)
            if (rowIds.length === 0) {
                Message.warning("请选择要执行计算的统计项！");
                return;
            }
            post({
                url: "ems/energyStatisticsResult/computeResultByExpr",
                data: exprList,
            }).then(({ code, data, message }: any) => {
                if (code === 200) {
                    Message.success({
                        content: "计算成功",
                        duration: 5000,
                    });
                    loadStatistics();
                }else{
                    Message.error({
                        content: message,
                        duration: 5000,
                    });
                }

            });
        }


        const  rowDoubleClicked=(event)=> {
             console.log(event.node);
             formData.formulaExpr = formData.formulaExpr + '{' + event.node.data.meterNo + '}';
        }


        const  evalExpr=()=> {
             let str = formData.formulaExpr;
             if(str.indexOf('}{')){
                 Message.error({
                     content: '请确认计算公式是否合法',duration: 5000
                 });
                 return;
             }
             let noArrs = str.match(/{[^}{]*?}/g);
             noArrs.forEach(c=>{
                 let meterNo = c.replace('{','').replace('}','')
                 let consume = consumeDataList.value.find(item=>item.meterNo===meterNo);
                 str = str.replaceAll(c,consume.thisCount);
             });
             try{
                 formData.result = eval(str);
             }catch(msg){
                 Message.error({
                     content: '请确认计算公式是否合法',
                     duration: 5000,
                 });
             }

        }


        return {
            pageChange,
            headerShow,
            pager,
            formData,
            rowDoubleClicked,
            consumeDataList,
            consumeGridReady,
            consumeGridOptions,
            consumeColDefs,
            columnDefs,
            initData,
            loadStatistics,
            loadDepartmentList,
            consumePageChange,
            computeStatistics,
            updateFormulas,
            consumeDataList,
            tableDataList,
            defaultColDef,
            gridOptions,
            gridReady,
            deleteHandler,
            showInsertForm,
            addStatistics,
            handleCancel,
            handleOk,
            evalExpr,
            formRef,
            pageData,
            searchData,
            localeTextData,
        };
    },

    components: { PageTabelLayout, CorporateSectorCascader }

};
</script>

<style scoped lang="less">
:deep(.ag-cell) {
    border-right: 1px solid #dde2eb;
}

:deep(.ag-header-cell) {
    border-right: 1px solid #dde2eb;
}

:deep(.ag-cell-value) {
    user-select: initial;
    -moz-user-select: text;
    -ms-user-select: text;
    -webkit-user-select: text;
}
</style>
